#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#




import wsgiref.handlers
import os

from google.appengine.ext import webapp



from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.api import urlfetch


class Category(db.Model):
	cid = db.IntegerProperty()
	name = db.StringProperty()

class Books(db.Model):
	name = db.StringProperty()
	descrption = db.TextProperty()
	date = db.DateTimeProperty(auto_now_add=True)
	tags = db.ListProperty(db.Key)
	category = db.IntegerProperty()
	visits = db.IntegerProperty()
	download = db.LinkProperty()
	
class Comments(db.Model):
	book = db.ReferenceProperty(Books,collection_name='comments')
	author = db.UserProperty()
	content = db.StringProperty(multiline=True)
	date = db.DateTimeProperty(auto_now_add=True)
	
class Tags(db.Model):
	tag = db.StringProperty()
	
	@property
	def entrys(self):
		return Entry.gql("where tags = :1" ,self.key())
		


	class SingleBlogHandler(webapp.RequestHandler):
		def get(self):

			query = db.Query(Entry)
			query.filter('')

class BookHandler(webapp.RequestHandler):
	def get(self):
		entries = Books.all().order('-date').fetch(limit=5)
		tags = {}
		for entry in entries:
			entry.fetched_tags = []
			for tag_key in entry.tags:
				if not tag_key in tags:
					tags[tag_key] = Tags.get(tag_key)
				entry.fetched_tags.append(tags[tag_key])

		if users.get_current_user():
			url = users.create_logout_url(self.request.uri)
			url_linktext = 'Logout'
		else:
			url = users.create_login_url(self.request.uri)
			url_linktext = 'Login'

		template_values = {
					'entries' : entries,
					'url' : url,
					'url_linktext' : url_linktext,
		}
		path = os.path.join(os.path.dirname(__file__), 'book.html')
		self.response.out.write(template.render(path, template_values))

class AddBookPage(webapp.RequestHandler):
	def get(self):
		template_values = {
			}
		path = os.path.join(os.path.dirname(__file__), 'addbook.html')
		self.response.out.write(template.render(path,template_values))


class AddBookHandler(webapp.RequestHandler):
	def post(self):
		entry = Books()
		entry.name = self.request.get('name')
		entry.description = self.request.get('description')
		entry.download = self.request.get('download')
		tag_string = self.request.get('tags')
		for tag_str in tag_string.split(','):
			tag = Tags()
			tag.tag = tag_str
			tag.put()
			if tag.key() not in entry.tags:
				entry.tags.append(tag.key())
		entry.put()
		self.redirect('/')

def main():
	application = webapp.WSGIApplication([('/',BookHandler),
	('/write',AddBookPage),
	('/add',AddBookHandler),
	],debug=True)
	wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
	main()
